//app.js
App({
	onLaunch: function () {
	    var app = wx.getStorageSync('userInfo');
	    if (app.openid && app.openid.length == 28) {
	      this.util.request({
	        url: 'entry/wxapp/ismem',
	        data: {openid:app.openid,m:'junsion_challeng'},
	        success: function (res) {
	          if(res.data == 1){
	            wx.navigateBack({});
	          }
	        },
	        app:this
	      });
	    }
	},
	onShow: function () {
	},
	onHide: function () {
	},
	onError: function (msg) {
		console.log(msg)
	},
	//加载微擎工具类
	util: require('we7/resource/js/util.js'),
	base64: require('we7/resource/js/base64.js'),
	md5: require('we7/resource/js/md5.js'),
	siteInfo : require('siteinfo.js'),
	getUserInfo : function (cb) {
		var app = wx.getStorageSync('userInfo');
		var that = this;
		if (app.avatar && app.openid && app.openid.length == 28) {
			wx.checkSession({
		        success: function () {
		          //session 未过期，并且在本生命周期一直有效
		          typeof cb == "function" && cb(app);
		        },
		        fail: function () {
		          //登录态过期
		          wx.login({
		            success: function (res) {
		              that.util.request({
		                url: 'entry/wxapp/openid',
		                data: { code: res.code, m: 'junsion_challeng' },
		              });
		              typeof cb == "function" && cb(app);
		            },
		          });
		        }
		      })
		}
		else {
			//调用登录接口
			var userInfo = {
				'openid': '',
				'nickname': '',
				'avatar': '',
			};
			wx.login({
				success: function (res) {
					that.util.request({
						url: 'entry/wxapp/openid',
						data: { code: res.code , m: 'junsion_challeng'},
						cachetime: 0,
						success: function (res) {
							userInfo['openid'] = res.data;
							wx.setStorageSync('userInfo', userInfo);
							wx.getUserInfo({
								success: function (wxInfo) {
									var info = JSON.parse(wxInfo.rawData);
									userInfo['nickname'] = info.nickName;
									userInfo['avatar'] = info.avatarUrl;
									userInfo['openid'] = res.data;
									wx.setStorage({key:'userInfo',data:userInfo});
								},
								complete: function() {
									typeof cb == "function" && cb(userInfo);
								}
							});
						}
					});
				},
			});
		}
	},
	sysInit: function(that,cb){
		var data = { m: 'junsion_challeng' };
		var timestamp =Date.parse(new Date());
		if(!wx.getStorageSync('music')){
			data.music = 1;
		}
		else{
			var music = wx.getStorageSync('music');
			if(parseInt(music['time'])>parseInt(timestamp)+86400000){
				data.music = 1;
			}else{
				data.music = 0;
			}
		}
		this.util.request({
			url: 'entry/wxapp/sysinfo',
			data: data,
			success: function (res) {
        if(res.data != -1){
        	var gnum = res.data.gnum;
		    if(gnum<=0){
		    	wx.showModal({
		    		title:'系统未开启任何游戏，请联系管理员',
		    		showCancel:false,
					success: function(res) {
						wx.navigateBack({});//关闭小程序
					}
		    	});
		    	return false;
		    }
		    
            var music = res.data.music
            if(music){
            	if(music.time>0){
    		    	wx.setStorage({key:'music',data:music});
    		    } 
            }
            var pages = getCurrentPages();
		    var currentPage = pages[pages.length - 1].route;
		    var gtype = parseInt(wx.getStorageSync('gameType'));
		    if (isNaN(gtype) || parseInt(res.data.check_status)==1){
		    	wx.setStorage({key:'gameType',data:parseInt(res.data.game)});
		    }
		    var color = res.data.color;
		    wx.setNavigationBarColor({ frontColor: '#ffffff', backgroundColor: color.project });
        that.setData({ gnum: gnum, footer: res.data.footer, color: color, check_status: res.data.check_status, currentPage: "/" + currentPage, advs: res.data.advs ? res.data.advs:null});
        }
        if(cb) cb(res);
			}
		});
	},
	getShareData: function(cb,openid,gtype){
		wx.showShareMenu({
			withShareTicket: true //要求小程序返回分享目标信息
		})
		if(!gtype) gtype='';
		this.util.request({
			url: 'entry/wxapp/share',
			data: { m: 'junsion_challeng',openid:openid,gtype:gtype},
			cachetime: 24*3600,
			success: function (res) {
				cb(res);
			}
		});
	},
	strencode:function(string,str_time){
		var key =this.md5(this.siteInfo.appkey+str_time);
        string = this.base64.base64_decode(string); 
        var len = key.length;   
        var code = '';   
        for (var i = 0; i < string.length; i++) {   
            var k = i % len;   
            code += String.fromCharCode(string.charCodeAt(i) ^ key.charCodeAt(k));   
        }   
        return decodeURIComponent(this.base64.base64_decode(code));   
	},
  getWidth: (str) => {
    return [].reduce.call(str, (pre, cur, index, arr) => {
      if (str.charCodeAt(index) > 255) {// charCode大于255是汉字
        pre++;
      } else {
        pre += 0.5;
      }
      return pre;
    }, 0);
  },
  getDuration: (str) => {// 保留，根据文字长度设置时间
    return this.getWidth() / 10;
  },
  checkReward:function(that,gtype,num){
	var app = this;
	app.util.request({
        url: 'entry/wxapp/GetReward',
        data: {
          m: 'junsion_challeng',
          t: 1,
          openid:that.data.openid,
          gametoken:that.data.gametoken,
          num:num,
          game:gtype,
        },
        success: function (res) {
        	if(res.data.code!=1){
        		wx.showModal({
	                  title:res.data.msg,
	                  showCancel:false,
	                  success: function(res) {
	                	  wx.showLoading({title:'数据加载中...'});
	                	  that.onLoad();
	                  }
                });
        	}
        	else{
        		var rid = res.data.id;
        		wx.showModal({
	                  title:'挑战成功，请前往完善信息',
	                  showCancel:false,
	                  success: function(res) {
	                	  wx.showLoading({title:'数据加载中...'});
	                	  wx.redirectTo({
	                		  url: '../tzfail/tzfail?rid='+rid
	      	    		  })
	                  }
                });
        	}
        },
    }); 
  },
  tzfail:function(that,gtype,num){
	  var app = this;
	  that.errAudio.play();
	  if(gtype!=1){
		  var num = that.data.cur_num;
	  }
	  app.util.request({
	    url: 'entry/wxapp/updateNum',
	    data: {
	      m: 'junsion_challeng',
	      t: 1,
	      openid:that.data.openid,
	      num:num,
	      game:gtype,
	    },
	    success: function (res) {
	      wx.showToast({
			title:'挑战失败',
			icon:'loading',
			mask:true,
			duration:1500,
			complete:function(){
			}
		});
	    setTimeout(function(){
	    	that.errAudio.pause()
	        wx.showLoading();
	    	wx.redirectTo({
	  	    	url: '../tzfail/tzfail'
	  	    })
	    },1500);
	    }
	  });
  },
  fRandomBy:function(under, over){
	switch(arguments.length){ 
		case 1: return parseInt(Math.random()*under+1); 
		case 2: return parseInt(Math.random()*(over-under+1) + under); 
		default: return 0; 
	}
  },
});
